package cn.itcast.itcaststore.dao.impl;

import cn.itcast.itcaststore.dao.UserDao;
import cn.itcast.itcaststore.domain.User;
import cn.itcast.itcaststore.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

public class UserDaoImpl implements UserDao {

    private QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
    @Override
    public void addUser(User user) throws SQLException {
        String sql = "insert into user(username,password,gender,email,telephone,introduce,activeCode) values(?,?,?,?,?,?,?)";
        int row = runner.update(sql, user.getUsername(), user.getPassword(), user.getGender(), user.getEmail(), user.getTelephone(), user.getIntroduce(), user.getActiveCode());
        if (row == 0) {
            throw new RuntimeException();
        }
    }

    @Override
    public User findUserByActiveCode(String activeCode)  throws SQLException {
        String sql = "select * from user where activeCode=?";
        return runner.query(sql, new BeanHandler<User>(User.class), activeCode);
    }

    @Override
    public int activeUser(String activeCode)  throws SQLException {
        String sql = "update user set state=? where activeCode=?";
       return runner.update(sql, 1, activeCode);
    }

    @Override
    public User findUserByUsernameAndPassword(String username, String password)  throws SQLException {
        String sql="select * from user where username=? and password=?";
        return runner.query(sql,new BeanHandler<User>(User.class),username,password);
    }
}
